package org.xc.uvc_camera

import android.util.Log
import com.qiniu.android.common.FixedZone
import com.qiniu.android.storage.Configuration
import com.qiniu.android.storage.UploadManager
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import org.xc.uvc_camera.net.QiNiuToken
import org.xc.uvc_camera.net.Req
import org.xc.uvc_camera.net.api.Other
import java.io.File

class UploadUtil {

    companion object {
        private val TAG: String = "UploadUtil"

        private var uploadInstance: UploadManager? = null

        init {
            uploadInstance = UploadManager(
                    Configuration.Builder()
                            .zone(FixedZone.zone2)
                            .build()
            )
        }

        fun uploadFile(filePath: String) {
            val file = File(filePath)
            if (file != null && file.exists()) {
                Log.e(TAG,"开始上传->" + file.absolutePath)
                //请求七牛上传Token
                Req.retrofit!!.create(Other::class.java).getQiNiuToken(SPUtil.getPlateNumber(App.context))
                        .subscribeOn(Schedulers.io())
                        .subscribe(object: Observer<QiNiuToken> {
                            override fun onComplete() {

                            }

                            override fun onSubscribe(d: Disposable) {

                            }

                            override fun onNext(t: QiNiuToken) {
                                if (t.code == 0) {
                                    uploadInstance!!.put(file,file.name,t.qiNiuToken, { key, info, response ->
                                        val fileUrl = "http://qiniu.whrobo.com/$key"
                                        //通知后台视频上传成功
                                        Req.retrofit!!.create(Other::class.java).videosUpload(fileUrl,SPUtil.getPlateNumber(App.context))
                                                .observeOn(Schedulers.io())
                                                .subscribeOn(Schedulers.newThread())
                                                .subscribe()
                                        //删除本地文件
//                                        file.delete()
                                    },null)
                                }
                            }

                            override fun onError(e: Throwable) {

                            }
                        })
            }
        }
    }

}